﻿using System.Security.Cryptography;
using System.Text;
using System.Text.RegularExpressions;

namespace Service.Framework.Utils.Extension
{
    public static class StringExtension
    {
        /// <summary>
        /// 判断字符串是否为数字
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public static Boolean IsNumber(this String str)
        {
            return Regex.IsMatch(str, "-?[0-9]*.?[0-9]*");

        }


        /// <summary>
        /// 转换为MD5加密后的字符串（默认加密为32位）
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public static string ToMD5String(this string str)
        {
            MD5 md5 = MD5.Create();
            byte[] inputBytes = Encoding.UTF8.GetBytes(str);
            byte[] hashBytes = md5.ComputeHash(inputBytes);

            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < hashBytes.Length; i++)
            {
                sb.Append(hashBytes[i].ToString("x2"));
            }
            md5.Dispose();
            return sb.ToString();
        }


        /// <summary>
        /// 转换为MD5加密后的字符串（16位）
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public static string ToMD5String16(this string str)
        {
            return str.ToMD5String().Substring(8, 16);
        }


        /// <summary>
        /// Base64加密
        /// </summary>
        /// <param name="source">待加密的明文</param>
        /// <param name="encoding">加密采用的编码方式</param>
        /// <returns></returns>
        public static string Base64Encode(this string source, Encoding encoding)
        {
            string encode = string.Empty;
            byte[] bytes = encoding.GetBytes(source);
            try
            {
                encode = Convert.ToBase64String(bytes);
            }
            catch
            {
                encode = source;
            }
            return encode;
        }

        /// <summary>
        /// Base64解密
        /// </summary>
        /// <param name="result">待解密的密文</param>
        /// <param name="encoding">解密采用的编码方式，注意和加密时采用的方式一致</param>
        /// <returns>解密后的字符串</returns>
        public static string Base64Decode(this string result, Encoding encoding)
        {
            string decode = string.Empty;
            byte[] bytes = Convert.FromBase64String(result);
            try
            {
                decode = encoding.GetString(bytes);
            }
            catch
            {
                decode = result;
            }
            return decode;
        }

        /// <summary>
        /// 华为云ObjecetKey生成
        /// </summary>
        /// <param name="FileType"></param>
        /// <param name="UserId"></param>
        /// <returns></returns>
        public static String ObjectKeyGenerator(this String FileType, Int32 UserId)
        {
            StringBuilder sb = new StringBuilder();
            sb.Append($"img/{UserId.ToString()}/");

            #region 加种子 随机数
            int iSeed = 61;
            Random ra = new Random(iSeed);

            int num = ra.Next(100, 300);
            #endregion 加种子 随机数

            sb.Append($"{num.ToString()}{GetTimeStamp()}.{FileType}");

            throw new NotImplementedException();
        }


        /// <summary>
        /// 获取时间戳
        /// </summary>
        /// <returns></returns>
        public static string GetTimeStamp()
        {
            TimeSpan ts = DateTime.Now - new DateTime(1970, 1, 1, 0, 0, 0, 0);
            return Convert.ToInt64(ts.TotalSeconds).ToString();
        }


        /// <summary>
        /// 将字符串转为可空的值类型
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="valueAsString"></param>
        /// <returns></returns>

        public static T? GetValueOrNull<T>(this string valueAsString) where T : struct
        {
            if (string.IsNullOrEmpty(valueAsString))
                return null;
            return (T)Convert.ChangeType(valueAsString, typeof(T));
        }

        /// <summary>
        /// 随机创建一个盐
        /// </summary>
        /// <param name="s"></param>
        /// <returns></returns>
        public static String CreateSalt(this String s)
        {
            System.Security.Cryptography.RNGCryptoServiceProvider RNG = new System.Security.Cryptography.RNGCryptoServiceProvider();
            byte[] buffer = new byte[32];
            RNG.GetBytes(buffer);
            var salt = BitConverter.ToString(buffer).Replace("-", string.Empty).ToLower();
            return salt;
        }

        /// <summary>
        /// 保留小数，并且不四舍五入
        /// </summary>
        /// <param name="num"></param>
        /// <param name="scale"></param>
        /// <returns></returns>
        public static string ToString(this decimal num, int scale)
        {
            string numToString = num.ToString();

            int index = numToString.IndexOf(".");
            int length = numToString.Length;

            if (index != -1)
            {
                return string.Format("{0}.{1}",
                    numToString.Substring(0, index),
                    numToString.Substring(index + 1, Math.Min(length - index - 1, scale)));
            }
            else
            {
                return num.ToString();
            }
        }




    }
}
